package com.rjwh.dingdong.client.activity.homework;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.adapter.HomeWorkRankListAdapter;
import com.rjwh.dingdong.client.bean.localbean.BannerData;
import com.rjwh.dingdong.client.bean.localbean.ScoreRankListItemData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.HomeWorkRankPresenter;
import com.rjwh.dingdong.client.mvp.view.HomeWorkRankView;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.view.IndicatorHackyViewPager;
import com.rjwh.dingdong.client.view.MySwipyRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author 王小珂
 * @ClassName HomeWorkRankActivity
 * @Description
 * @date 2017-1-4
 * @history 2017-1-4 author: description:
 */

public class HomeWorkRankActivity extends BaseActivity implements HomeWorkRankView {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.home_work_rank_listview)
    ListView homeWorkRankListview;
    @BindView(R.id.home_work_rank_mPullRefreshView)
    MySwipyRefreshLayout homeWorkRankMPullRefreshView;

    private HomeWorkRankListAdapter adapter;
    private HomeWorkRankPresenter presenter;
    private int pageNumber;
    private MenuItem menuItem;
    private String duration = "";
    private IndicatorHackyViewPager viewPager;
    private MyPagerAdapter myPagerAdapter;
    private View headerView;
    private TimeCount time;

    public static void startActivity(Context context, String duration) {
        Intent intent = new Intent(context, HomeWorkRankActivity.class);
        intent.putExtra(LocalConstant.ACTIONURL_DURATION, duration);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_work_rank_layout);
        ButterKnife.bind(this);
        parseIntent();
        initView();
        presenter = new HomeWorkRankPresenter(this, this);
        homeWorkRankMPullRefreshView.doPullRefreshing();
    }


    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            duration = intent.getStringExtra(LocalConstant.ACTIONURL_DURATION);
        }
    }

    private void initView() {
        initToolbarHelper();

        initListViewHeader();

        adapter = new HomeWorkRankListAdapter(this);
        homeWorkRankListview.setAdapter(adapter);

        homeWorkRankMPullRefreshView.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                switch (direction) {
                    case TOP:
                        pageNumber = 0;
                        doGetHomeWorkRankList(true, SwipyRefreshLayoutDirection.TOP);
                        break;
                    case BOTTOM:
                        pageNumber++;
                        doGetHomeWorkRankList(false, SwipyRefreshLayoutDirection.BOTTOM);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void initListViewHeader() {
        LinearLayout headerParent = new LinearLayout(this);
        headerView = View.inflate(getApplicationContext(), R.layout.home_work_rank_list_header, null);
        viewPager = (IndicatorHackyViewPager) headerView.findViewById(R.id.home_work_rank_list_header_viewpager);
        myPagerAdapter = new MyPagerAdapter();
        viewPager.setAdapter(myPagerAdapter);
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        cancelTimer();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (myPagerAdapter.getCount() > 2) {
                            startTimer();
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

        headerParent.addView(headerView);
        homeWorkRankListview.addHeaderView(headerParent);
        //默认隐藏header,有数据时再显示
        headerView.setVisibility(View.GONE);
    }

    private void doGetHomeWorkRankList(boolean isRefresh, SwipyRefreshLayoutDirection direction) {
        presenter.doGetHomeWorkList(duration, pageNumber, isRefresh, direction);
    }

    /**
     * init the toolbar
     */
    protected void initToolbarHelper() {
        toolbar.setTitle("");
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.homework_rank);
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_homework_rule, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menuItem = menu.findItem(R.id.menu_homework_rule);
        menuItem.setVisible(false);
        return super.onPrepareOptionsMenu(menu);
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (myPagerAdapter == null) {
                return;
            }
            int count = myPagerAdapter.getCount();
            if (count > 2) { // 多于2个，才循环
                int index = viewPager.getCurrentItem();
                index = (index + 1) % count;
                viewPager.setCurrentItem(index, true);
                startTimer();
            } else {
                cancelTimer();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    public class MyPagerAdapter extends PagerAdapter {

        private List<BannerData> bannerlist = new ArrayList<>();

        public void addList(List<BannerData> list) {
            if (list != null) {
                bannerlist.clear();
                bannerlist.addAll(list);
                notifyDataSetChanged();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(HomeWorkRankActivity.this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (bannerlist.get(position).getBannerurl() != null) {
                Glide.with(HomeWorkRankActivity.this).load(bannerlist.get(position).getBannerurl()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(imageView);
            }
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //banner图跳转
                    String actionurl = bannerlist.get(position).getActionurl();
                    if (actionurl != null) {
                        UrlUtil.handelUrl(HomeWorkRankActivity.this, actionurl, true);
                    }
                }
            });
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return bannerlist == null ? 0 : bannerlist.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        homeWorkRankMPullRefreshView.setRefreshing(isRefresh);
    }

    @Override
    public void setDirection(SwipyRefreshLayoutDirection direction) {
        homeWorkRankMPullRefreshView.setDirection(direction);
    }

    @Override
    public void loadData(boolean isRefresh, List<ScoreRankListItemData> homeworklist) {
        if (isRefresh) {
            adapter.clearAll();
        }
        adapter.appendToList(homeworklist);
    }

    @Override
    public void setRuleData(final String ruleactionurl, String ranktitle) {
        if (!AsStrUtils.isEmpty(ruleactionurl)) {
            menuItem.setVisible(true);
            menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    UrlUtil.handelUrl(HomeWorkRankActivity.this, ruleactionurl, true);
                    return true;
                }
            });
        }
        if (!AsStrUtils.isEmpty(ranktitle)) {
            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle(ranktitle);
            }
        }
    }

    @Override
    public void setBannerData(List<BannerData> bannerlist) {
        if (bannerlist.size() > 3) {
            if (time == null) {
                time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
            }
        }
        if (bannerlist.isEmpty()) {
            headerView.setVisibility(View.GONE);
        } else {
            headerView.setVisibility(View.VISIBLE);
            myPagerAdapter.addList(bannerlist);
        }
        startTimer();
    }

    private void startTimer() {
        if (time != null) {
            time.start();
        }
    }

    private void cancelTimer() {
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onPause() {
        super.onPause();
        cancelTimer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimer();
        time = null;
        presenter.detachView();
    }
}
